import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { TextArea } from '@/components/textarea';
import { useAppSelector } from '@/store';
import {
  getUserPhotoAction,
  getUserProfileAction,
  updateUserAction,
} from '@/store/action/user';
import { ProfileType } from '@/store/redurce/user';
import { removeTokenInfo } from '@/utils/storage';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styles from './index.module.scss';

export default function ProfileEdit() {
  // 声明一个类型:EditType
  type EditType = 'photo' | 'gender' | 'intro' | 'name';
  // 声明一个状态 editType
  const [editType, setEditType] = useState('' as EditType);

  // 给input声明ref
  const inputRef = useRef<HTMLInputElement>(null);
  // 封装复用弹出层的点击事件
  const handleShowToast = (editType: EditType) => {
    setVisible(true);
    setEditType(editType);
  };

  // 😀点击小灯泡自动生成
  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log('e  ----->  ', e);
    const formData = new FormData();
    if (e.target.files) {
      formData.append('photo', e.target.files[0]);
    }
    await dispatch(getUserPhotoAction(formData));
    setVisible(false);
    Toast.show({ content: '更新成功' });
  };

  // 1. 声明转态，控制右侧弹出层显示
  const [rightVisible, setRightVisible] = useState(false);
  const { profile } = useAppSelector((state) => state.user);
  const [visible, setVisible] = useState(false);
  const [name, setName] = useState(profile.name);
  const [intro, setIntro] = useState('123');
  const [birthVisible, setBirthVisible] = useState(false);
  const dispatch = useDispatch();
  const history = useHistory();
  useEffect(() => {
    dispatch(getUserProfileAction());
  }, [dispatch]);
  // 5.获取数据,渲染页面 , 记得用useAppSelector,不要用useSelector

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleUpdateProfile({ name });
    }
  };
  // 监听name ,有变化时设置给初始值
  useEffect(() => {
    setName(profile.name);
  }, [profile.name]);

  useEffect(() => {
    setIntro(profile.intro);
  }, [profile.intro]);

  const handleBack = () => {
    setRightVisible(false);
    if (editType === 'name') setName(profile.name);
    if (editType === 'intro') setIntro(profile.name);
  };

  const handleSubmit = () => {
    if (editType === 'name') handleUpdateProfile({ name });
    if (editType === 'intro') handleUpdateProfile({ intro });
  };
  const handleLoginOut = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '亲，您确定要退出吗？',
      onConfirm: () => {
        // 1. 清token, removeAuth
        // 2. 跳转路由，跳转登录
        removeTokenInfo();
        history.push('/login');
      },
    });
  };
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              onClick={() => handleShowToast('photo')}
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
            >
              头像
            </List.Item>

            {/* 4. 点击修改editTYpe的值 */}
            <List.Item
              arrow
              extra={profile.name}
              onClick={() => {
                setEditType('name');
                setRightVisible(true);
              }}
            >
              昵称
            </List.Item>

            <List.Item
              onClick={() => {
                setEditType('intro');
                setRightVisible(true);
              }}
              arrow
              extra={<span className="intro">{profile.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 1 ? '女' : '男'}
              onClick={() => handleShowToast('gender')}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={() => setBirthVisible(true)}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input
            ref={inputRef}
            className="avatar-upload"
            type="file"
            onChange={(e) => handleChange(e)}
          />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLoginOut}>
            退出登录
          </button>
        </div>
      </div>

      {/* 底部弹出层 */}
      <Popup
        visible={visible}
        onMaskClick={() => setVisible(false)}
        position="bottom"
        bodyClassName="popup-bottom-list"
      >
        {/* 条件渲染不同的内容 */}
        {/* render开头,表示渲染JSX内容 */}
        {renderBottom()}
        <div className="list-item" onClick={() => setVisible(false)}>
          取消
        </div>
      </Popup>
      {/* 2. 使用弹出层 */}
      <Popup
        visible={rightVisible}
        // 6. 点击关闭
        onMaskClick={() => setRightVisible(false)}
        position="right"
        bodyClassName="popup-right"
        // Antd为了性能考虑,默认关闭弹出层时不卸载内容
        // destroyOnClose可以通知antd,卸载内容
        destroyOnClose
      >
        {renderRight()}
      </Popup>
      <DatePicker
        title="生日选择"
        visible={birthVisible}
        onClose={() => setBirthVisible(false)}
        value={new Date(profile.birthday)}
        onConfirm={(val) => {
          console.log('val  ----->  ', val.toDateString());
          handleUpdateProfile({ birthday: dayjs(val).format('YYYY-MM-DD') });
        }}
      ></DatePicker>
    </div>
  );
  function renderBottom() {
    if (editType === 'photo') {
      return (
        <>
          {/* 删除原来的handleClick事件 */}
          <div className="list-item" onClick={() => inputRef.current?.click()}>
            拍照
          </div>
          <div className="list-item" onClick={() => inputRef.current?.click()}>
            本地选择
          </div>
        </>
      );
    }
    if (editType === 'gender') {
      return (
        <>
          <div
            className="list-item"
            onClick={() => handleUpdateProfile({ gender: 0 })}
          >
            男
          </div>
          <div
            className="list-item"
            onClick={() => handleUpdateProfile({ gender: 1 })}
          >
            女
          </div>
        </>
      );
    }
  }
  async function handleUpdateProfile(profile: Partial<ProfileType>) {
    await dispatch(updateUserAction(profile));
    Toast.show({ content: '更新成功' });
    setVisible(false);
    setRightVisible(false);
  }
  // 5. 根据editType渲染不同的内容
  function renderRight() {
    let value = '';
    if (editType === 'name') value = name;
    if (editType === 'intro') value = intro;
    return (
      <>
        <NavBar
          onBack={handleBack}
          right={
            <span className="submit-btn" onClick={handleSubmit}>
              提交
            </span>
          }
        >
          编辑
          {editType === 'name' && '昵称'}
          {editType === 'intro' && '简介'}
        </NavBar>
        {editType === 'name' && (
          <div>
            <TextArea
              value={intro}
              onChange={(e) => setIntro(e.target.value)}
              className="123"
            ></TextArea>
          </div>
        )}
        {editType === 'intro' && (
          <Input
            className="edit-input"
            value={name}
            onChange={(e) => setName(e.target.value)}
            autoFocus
            onKeyDown={(e) => handleKeyDown(e)}
          />
        )}
      </>
    );
    // if (editType === 'intro') {
    //   return (
    //     <>
    //       <NavBar
    //         onBack={handleBack}
    //         right={
    //           <span className="submit-btn" onClick={handleSubmit}>
    //             提交
    //           </span>
    //         }
    //       >
    //         编辑用户信息
    //       </NavBar>
    //       <div>
    //         <TextArea
    //           value={intro}
    //           onChange={(e) => setIntro(e.target.value)}
    //           className="123"
    //         ></TextArea>
    //       </div>
    //     </>
    //   );
    // }

    // if (editType === 'name') {
    //   return (
    //     <>
    //       <NavBar
    //         onBack={handleBack}
    //         right={
    //           <span className="submit-btn" onClick={handleSubmit}>
    //             提交
    //           </span>
    //         }
    //       >
    //         编辑用户信息
    //       </NavBar>
    //       <div className="edit-content">
    //         <h3 className="edit-title">编辑昵称</h3>
    //         <Input
    //           className="edit-input"
    //           value={name}
    //           onChange={(e) => setName(e.target.value)}
    //           autoFocus
    //           onKeyDown={(e) => handleKeyDown(e)}
    //         />
    //       </div>
    //     </>
    //   );
    // }
  }
}
